<?php


namespace App\Service;

use App\Common\Tools\DbTools;
use App\Model\FlyShop;
use App\Model\ProductAudit;
use App\Model\Product;
use App\Model\ProductAuditRefuse;
use Hyperf\DbConnection\Db;
use mysql_xdevapi\Exception;
Use Hyperf\Di\Annotation\Inject;

/**
 * 商品审核
 * Class ProductAuditService
 * @package App\Service
 */
class ProductAuditService extends BaseService
{

    /**
     * 审核
     * @Inject
     * @var ProductAuditRefuseService
     */
    private $ProductAuditRefuseService;
    /**
     * @Inject
     * @var EsService
     */
    private $es;
    /**
     * 列表
     * @param array $request_param
     * @param int $type
     * @return \Hyperf\Database\Model\Builder
     */
    public function index(array $request_param,$type=1): \Hyperf\Database\Model\Builder
    {

        return ProductAudit::query()
            ->where('audit_type',$type)
            ->where(function ($query) use ($request_param) {
                //状态筛选
                if (isset($request_param['audit_status'])&&[]!=$request_param['audit_status']) {
                    $query->whereIn('audit_status', $request_param['audit_status']);
                }

                if (isset($request_param['key_word'])&&''!=$request_param['key_word']) {
                    $shop_ids =  FlyShop::query()->where('shop_name','like','%'.$request_param['key_word'].'%')->pluck('id');
                    if($shop_ids){
                        $shop_ids = $shop_ids->toArray();
                    }
                    $query->whereIn('shop_id', $shop_ids)
                        ->orWhere(...DbTools::sqlLikePro('product_name', $request_param['key_word']));
                }
                //商铺
                if (isset($request_param['shop_name'])&&''!=$request_param['shop_name']) {
                    $shop_ids =  FlyShop::query()->where('shop_name','like','%'.$request_param['shop_name'].'%')->pluck('id');
                   if($shop_ids){
                       $shop_ids = $shop_ids->toArray();
                   }
                   $query->whereIn('shop_id', $shop_ids);
                }
                //商品
                if (isset($request_param['product_name']) && !empty($request_param['product_name'])) {
                    $query->where(...DbTools::sqlLikePro('product_name', $request_param['product_name']));
                }

                //$industry_id 行业id
                if (isset($request_param['industry_id']) && !empty($request_param['industry_id'])) {
                    $query->where('industry_id', intval($request_param['industry_id']));
                }
            })
            ->with(['create_info','update_info','delete_info'])
            ->with(['link_channel_audit', 'main_pic_audit', 'detail_pic_audit','industry_info'
                ,'sku_list'
                ,'landmark_info','file_info', 'specialty_info','shop_info'])
            ->with(['reason_info','refuse_info'])
            ->orderBy('created_at');
    }

    /**
     * 单个详情
     * @param int $id
     * @return \Hyperf\Database\Model\Builder
     */
    public function info($id): \Hyperf\Database\Model\Builder
    {
        return ProductAudit::query()
//            ->with(['link_channel_audit', 'main_pic_audit', 'detail_pic_audit', 'industry_info','file_info','shop_info'])
//            ->with(['reason_info','refuse_info'])

            ->with(['create_info','update_info','delete_info'])
            ->with(['link_channel_audit', 'main_pic_audit', 'detail_pic_audit',
                'industry_info','landmark_info','file_info'
                ,'sku_list',
                'specialty_info','shop_info'])
            ->with(['reason_info','refuse_info'])
            ->where('id',$id)->first();
    }


    /**
     * 统计
     * @param int $type
     * @return array
     */
    public function countSize($type=1)
    {
        if(in_array($type,[1,2])){
            $audit_count = ProductAudit::query()
                ->where('audit_type',$type)
                ->selectRaw("
                count(case when audit_status !=3 then 1 end) as total_num,
                count(case when audit_status = 0 then 1 end) as checking_num,
                count(case when audit_status = 1 then 1 end) as checked_num,
                count(case when audit_status = -1 then 1 end) as refuse_num")
                ->first();
            return $audit_count;
        }else{
            return [];
        }
    }

    /**
 * 审计同意
 * @param int $id
 * @param int $user_id
 * @param int $type  1认证审核 2违规审核
 * @return bool
 */

    public function agrees($id,$user_id,$type=1)
    {
        Db::beginTransaction();
        try{
                $audit_model = (New ProductAudit())->find($id);
                $product_id = $audit_model->product_id;
                $audit_model->audit_by = $user_id;
                $audit_model->audit_at = date('Y-m-d H:i:s');
                $audit_model->audit_status = 1;
                $audit_model->save();
                if($type==1){
                    Product::query()->where('id',$product_id)->update(['check_status'=>1]);
                }else{
                    Product::query()->where('id',$product_id)->update(['is_illegal'=>0]);
                }

                Db::commit();
                //通过，更新es
                $this->es_push($id,1);
                return true;
        }     catch (\Throwable $exception) {

            Db::rollBack();
            return false;
        }
    }

    /**
     * @param array $reason
     * @param int $user_id
     * @param int $type  1认证审核 2违规审核
     * @return bool
     */
    //驳回，不更新es，需要驳回原因
    public function refuse($reason,$user_id,$type=1)
    {
        Db::beginTransaction();
        try{
            $audit_model = (New ProductAudit())->find($reason['id']);
            $product_id = $audit_model->product_id;
            $audit_model->audit_by = $user_id;
            $audit_model->audit_at = date('Y-m-d H:i:s');
            $audit_model->audit_status = -1;
            $audit_model->save();
            if($type==1){
                Product::query()->where('id',$product_id)->update(['check_status'=>-1]);
            }
//            if($type==2){
//                Product::query()->where('id',$product_id)->update(['check_status'=>-1]);
//            }

            $this->ProductAuditRefuseService->refuse_insert($reason['id'],$reason['reasons'],$reason['tips']);
            Db::commit();
            return true;
        }     catch (\Throwable $exception) {
            Db::rollBack();
            return false;
        }
    }

    /**
     *
     * 同步进es
     * @param int $id
     * @param int $type  1商品 2商家 3.....
     */
    public function syncDrive($id,$type)
    {

    }

    /**
     * 获取审核的通过的
     * @param int $product_id
     * @param bool $cross
     * @return object
     */
    public function old_info($product_id,$cross=1)
    {
        return $this->getModelInstance()
            ->when($cross,function ($query){
                $query->where('audit_status',1);
            })
            ->with([
                'landmark_info','link_channel_audit'])
            ->where('product_id',$product_id)
            ->orderBy('id','DESC')
            ->first();
    }
}